import { useMap, useMount } from "ahooks";
import { isNil, isPlainObject } from "lodash-es";

import useList from "./useList";
import ApiApp from "@/api/app";

type UseEnumOption = {
  label: string | number;
  value: string | number;
  [key: string]: any;
};

export default (defaultOptions?: UseEnumOption[] | { className: string }) => {
  const [_, { set, get }] = useMap<string | number, UseEnumOption>();

  const { list } = useList<{
    id: number;
    code: number;
    name: string;
    [key: string]: any;
  }>(ApiApp.dictionaryList, {
    manual: !isPlainObject(defaultOptions),
    defaultParams: [defaultOptions],
    onAfter: ({ list }) => {
      return {
        list: list.map((e) => ({
          ...e,
          value: e.id,
          label: e.name,
        })),
      };
    },
  });

  const setToMap = (options: UseEnumOption[]) => {
    options?.forEach((e) => set(e.value ?? e.label, e));
  };

  useMount(() => {
    if (Array.isArray(defaultOptions)) setToMap(defaultOptions);
  });

  const getOption = (key?: any, property?: string | number) => {
    if (!isNil(key)) {
      const target = get(key);

      return property && target ? target[property] : target;
    }
  };

  return { options: list, getOption };
};
